package dt.inlee.system.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.pagination.ConditionBean;
import dt.inlee.common.pagination.ConditionType;
import dt.inlee.common.pagination.PageBean;
import dt.inlee.common.pagination.SearchBean;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.domain.SysUser;
import dt.inlee.system.model.KqSysrole;
import dt.inlee.system.model.KqSysroleDept;
import dt.inlee.system.service.KqSysroleDeptService;
import dt.inlee.system.service.KqSysroleService;
import dt.inlee.system.service.SysUserService;
import dt.inlee.system.vo.SysUserLoginBean;

public class KqSysroleAction extends ActionSupport {
    /**
     * @Fields serialVersionUID : TODO()
     */
    private static final long serialVersionUID = 6993714998981428753L;
    // 角色信息业务层
    @Autowired
    private KqSysroleService kqSysroleService;
    // 角色部门权限业务层
    @Autowired
    private KqSysroleDeptService kqSysroleDeptService;
    @Autowired
    private SysUserService sysUserService;

    // JSON对象
    private JSONObject json;

    private String id;

    private String deptIds;

    public String getDeptIds() {
        return deptIds;
    }

    public void setDeptIds(String deptIds) {
        this.deptIds = deptIds;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public JSONObject getJson() {
        return json;
    }

    public void setJson(JSONObject json) {
        this.json = json;
    }

    /**
     * 查询角色列表信息
     * 
     * @return
     */
    @Action(value = "findRoleList", results = {@Result(type = "json", name = "success", params = {"root", "json"})})
    public String findRoleList() {
        try {
            SysUserLoginBean sysUserLoginBean =
                    (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
            SysUser loginUser = null;
            try {
                loginUser = this.sysUserService.findSysUserById(sysUserLoginBean.getId());
            } catch (FrameworkException e) {
                e.printStackTrace();
            }
            int wyId = loginUser.getWyId();

            SearchBean sb = new SearchBean();
            sb.addCondition(new ConditionBean("", ConditionType.ORBYVALUE, new Object[] {
                    Restrictions.like(KqSysrole.COL_ENTERPRISEID, wyId),
                    Restrictions.isNull(KqSysrole.COL_ENTERPRISEID)}));

            int rows = Integer.parseInt((String) ServletActionContext.getRequest().getParameter("rows"));
            // 当前页码数
            int page = Integer.parseInt((String) ServletActionContext.getRequest().getParameter("page"));
            // 分页查询数据
            PageBean pageBeans = kqSysroleService.getList(sb, rows, page);
            // 数据列表
            @SuppressWarnings("unchecked")
            List<KqSysrole> kqSysroleList = (List<KqSysrole>) pageBeans.getResults();
            // 总条数
            int count = pageBeans.getTotalData();

            Map<String, Object> jsonMap = new HashMap<String, Object>();
            // ui需要实现数据的总记录数
            jsonMap.put("rows", kqSysroleList);
            jsonMap.put("total", count);
            json = JSONObject.fromObject(jsonMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;

    }

    /**
     * 查找此企业顶部部门
     * 
     * @return
     */
    // @Action(value = "findFatherDeptId", results = { @Result(type = "json", name = "success", params = {
    // "root", "json" }) })
    // public String findFatherDeptId(){
    // SysUserLoginBean sysUserLoginBean = (SysUserLoginBean) ActionContext
    // .getContext().getSession().get(CommonConstant.SESSION_USER);
    // SysUser loginUser = null;
    // try {
    // loginUser = this.sysUserService.findSysUserById(sysUserLoginBean
    // .getId());
    // } catch (FrameworkException e) {
    // e.printStackTrace();
    // }
    // int wyId = loginUser.getWyId();
    //
    // SearchBean deptId = new SearchBean();
    // deptId.addCondition(new ConditionBean(DepartmentEntity.COL_SUBCOMPANY_ENTITY,ConditionType.EQUAL,new Object[]{wyId}));
    // deptId.addCondition(new ConditionBean(DepartmentEntity.COL_BELONGID,ConditionType.EQUAL,new Integer[]{0}));
    // List<DepartmentEntity> list = departmentService.getList(deptId);
    // int deptIdFather = list.get(0).getId();
    // Map<String, Object> jsonMap = new HashMap<String, Object>();
    // jsonMap.put("deptid", deptIdFather+"");
    // json = JSONObject.fromObject(jsonMap);
    // return SUCCESS;
    // }

    /**
     * 查询角色部门
     * 
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Action(value = "findRoleDepts", results = {@Result(type = "json", name = "success", params = {"root", "json"})})
    public String findRoleDepts() {
        List deptIds = new ArrayList();
        SearchBean sb = new SearchBean();
        sb.addCondition(new ConditionBean(KqSysroleDept.COL_SYSROLEID, ConditionType.EQUAL, new Object[] {id}));
        List<KqSysroleDept> sysroleDeptList = kqSysroleDeptService.getList(sb);
        for (int i = 0; i < sysroleDeptList.size(); i++) {
            if (BaseUtil.isEmpty(sysroleDeptList.get(i).getSysDeptId()))
                deptIds.add(0);
            else {
                deptIds.add(sysroleDeptList.get(i).getSysDeptId());
            }

        }
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        // ui需要实现数据的总记录数
        jsonMap.put("deptIds", deptIds);
        json = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 保存角色部门信息
     * 
     * @return
     */
    @Action(value = "saveRoleDept", results = {@Result(type = "json", name = "success", params = {"root", "json"})})
    public String saveRoleDept() {
        SearchBean sb = new SearchBean();
        sb.addCondition(new ConditionBean(KqSysroleDept.COL_SYSROLEID, ConditionType.EQUAL, new Object[] {id}));
        List<KqSysroleDept> roleDeptList = kqSysroleDeptService.getList(sb);
        for (int i = 0; i < roleDeptList.size(); i++) {
            kqSysroleDeptService.deleteById(roleDeptList.get(i).getId());
        }
        String[] ids = deptIds.split(",");
        for (String string : ids) {
            String deptId = string;
            KqSysroleDept kqSysroleDept = new KqSysroleDept();
            kqSysroleDept.setSysDeptId(deptId);
            kqSysroleDept.setSysRoleId(id);
            kqSysroleDeptService.save(kqSysroleDept);
        }
        return SUCCESS;
    }
}
